// 检查登录状态
function checkLoginStatus() {
    fetch('/api/auth/check', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        if (response.status === 401) {
            window.location.href = '/login.html';
        }
    })
    .catch(error => {
        console.error('Error checking login status:', error);
    });
}

// 页面加载时检查登录状态
document.addEventListener('DOMContentLoaded', function() {
    checkLoginStatus();
    loadServerList();
    
    // 添加服务按钮点击事件
    document.getElementById('addServerBtn').addEventListener('click', function() {
        document.getElementById('serverModalTitle').textContent = '添加服务';
        document.getElementById('serverId').value = '';
        document.getElementById('serverName').value = '';
        document.getElementById('serverType').value = 'TCP';
        document.getElementById('serverPort').value = '';
        document.getElementById('responseMode').value = 'MANUAL';
        document.getElementById('responseContent').value = '';
        
        updateResponseContentVisibility();
        
        const serverModal = new bootstrap.Modal(document.getElementById('serverModal'));
        serverModal.show();
    });
    
    // 保存服务按钮点击事件
    document.getElementById('saveServerBtn').addEventListener('click', saveServer);
    
    // 响应模式变化事件
    document.getElementById('responseMode').addEventListener('change', updateResponseContentVisibility);
    
    // 退出登录按钮点击事件
    document.getElementById('logoutBtn').addEventListener('click', logout);
});

// 加载服务器列表
function loadServerList() {
    fetch('/api/servers')
        .then(response => response.json())
        .then(servers => {
            const serverList = document.getElementById('serverList');
            serverList.innerHTML = '';
            
            servers.forEach(server => {
                const li = document.createElement('li');
                li.className = 'list-group-item server-item';
                li.innerHTML = `
                    <div class="server-info">
                        <strong>${server.name}</strong> (${server.type})
                        <div>端口: ${server.port}</div>
                        <div>响应模式: ${getResponseModeName(server.responseMode)}</div>
                    </div>
                    <div class="server-status">
                        <span class="status-badge ${server.running ? 'status-running' : 'status-stopped'}"></span>
                        ${server.running ? '运行中' : '已停止'}
                    </div>
                    <div class="btn-group ms-2">
                        <button class="btn btn-sm btn-outline-primary view-btn" data-server-id="${server.id}">查看</button>
                        <button class="btn btn-sm ${server.running ? 'btn-outline-danger stop-btn' : 'btn-outline-success start-btn'}" 
                                data-server-id="${server.id}">
                            ${server.running ? '停止' : '启动'}
                        </button>
                        <button class="btn btn-sm btn-outline-secondary edit-btn" data-server-id="${server.id}">编辑</button>
                        <button class="btn btn-sm btn-outline-danger delete-btn" data-server-id="${server.id}">删除</button>
                    </div>
                `;
                serverList.appendChild(li);
                
                // 添加按钮事件
                li.querySelector('.view-btn').addEventListener('click', () => viewServer(server));
                li.querySelector(server.running ? '.stop-btn' : '.start-btn').addEventListener('click', () => {
                    if (server.running) {
                        stopServer(server.id);
                    } else {
                        startServer(server.id);
                    }
                });
                li.querySelector('.edit-btn').addEventListener('click', () => editServer(server));
                li.querySelector('.delete-btn').addEventListener('click', () => deleteServer(server.id));
            });
        })
        .catch(error => console.error('Error loading servers:', error));
}

// 查看服务器
function viewServer(server) {
    // 检查是否已存在该服务器的标签页
    let tab = document.getElementById(`tab-${server.id}`);
    
    if (!tab) {
        // 创建新的标签页
        const tabsNav = document.getElementById('serverTabs');
        const tabContent = document.getElementById('serverTabContent');
        
        // 创建标签
        const tabLi = document.createElement('li');
        tabLi.className = 'nav-item';
        tabLi.innerHTML = `
            <a class="nav-link" id="tab-${server.id}" data-bs-toggle="tab" href="#content-${server.id}">
                ${server.name}
                <button class="btn-close ms-2" aria-label="Close"></button>
            </a>
        `;
        tabsNav.appendChild(tabLi);
        
        // 创建内容
        const contentDiv = document.createElement('div');
        contentDiv.className = 'tab-pane fade';
        contentDiv.id = `content-${server.id}`;
        contentDiv.innerHTML = `
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h4>${server.name} (${server.type})</h4>
                <div>
                    <span class="badge ${server.running ? 'bg-success' : 'bg-danger'}">
                        ${server.running ? '运行中' : '已停止'}
                    </span>
                    <span class="badge bg-secondary">端口: ${server.port}</span>
                    <span class="badge bg-info">${getResponseModeName(server.responseMode)}</span>
                </div>
            </div>
            
            <h5>连接列表</h5>
            <div class="connection-list mb-4">
                <div class="list-group" id="connections-${server.id}">
                    <div class="text-center p-3 text-muted">暂无连接</div>
                </div>
            </div>
            
            <div id="message-panel-${server.id}" style="display: none;">
                <h5>消息</h5>
                <div class="message-container" id="messages-${server.id}"></div>
                
                <div class="mb-3">
                    <label for="message-input-${server.id}" class="form-label">发送消息</label>
                    <textarea class="form-control" id="message-input-${server.id}" rows="3"></textarea>
                </div>
                
                <div class="d-flex justify-content-between mb-3">
                    <div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="content-type-${server.id}" 
                                   id="text-type-${server.id}" value="TEXT" checked>
                            <label class="form-check-label" for="text-type-${server.id}">文本</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="content-type-${server.id}" 
                                   id="hex-type-${server.id}" value="HEX">
                            <label class="form-check-label" for="hex-type-${server.id}">十六进制</label>
                        </div>
                    </div>
                    <button class="btn btn-primary" id="send-btn-${server.id}">发送</button>
                </div>
            </div>
        `;
        tabContent.appendChild(contentDiv);
        
        // 添加关闭标签事件
        tabLi.querySelector('.btn-close').addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            // 如果当前标签是活动的，则切换到欢迎标签
            if (tabLi.querySelector('.nav-link').classList.contains('active')) {
                document.getElementById('welcome-tab').click();
            }
            
            // 移除标签和内容
            tabLi.remove();
            contentDiv.remove();
        });
        
        // 添加发送消息事件
        contentDiv.querySelector(`#send-btn-${server.id}`).addEventListener('click', function() {
            const connectionId = contentDiv.querySelector('.connection-item.active')?.dataset.connectionId;
            if (!connectionId) return;
            
            const message = document.getElementById(`message-input-${server.id}`).value;
            const contentType = document.querySelector(`input[name="content-type-${server.id}"]:checked`).value;
            
            sendMessage(connectionId, message, contentType);
        });
        
        // 加载连接列表
        loadConnections(server.id);
        
        // 设置WebSocket连接以接收实时更新
        setupWebSocket();
        
        tab = tabLi.querySelector('.nav-link');
    }
    
    // 激活标签
    tab.click();
}

// 加载连接列表
function loadConnections(serverId) {
    fetch(`/api/servers/${serverId}/connections`)
        .then(response => response.json())
        .then(connections => {
            const connectionsList = document.getElementById(`connections-${serverId}`);
            connectionsList.innerHTML = '';
            
            if (connections.length === 0) {
                connectionsList.innerHTML = '<div class="text-center p-3 text-muted">暂无连接</div>';
                return;
            }
            
            connections.forEach(connection => {
                const li = document.createElement('a');
                li.href = '#';
                li.className = 'list-group-item list-group-item-action connection-item';
                li.dataset.connectionId = connection.id;
                li.innerHTML = `
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <strong>${connection.remoteAddress}:${connection.remotePort}</strong>
                            <div class="text-muted small">连接时间: ${formatDateTime(connection.connectedTime)}</div>
                        </div>
                        <span class="badge ${connection.active ? 'bg-success' : 'bg-danger'}">
                            ${connection.active ? '活动' : '断开'}
                        </span>
                    </div>
                `;
                connectionsList.appendChild(li);
                
                // 添加点击事件
                li.addEventListener('click', function(e) {
                    e.preventDefault();
                    
                    // 移除其他连接的活动状态
                    connectionsList.querySelectorAll('.connection-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    
                    // 设置当前连接为活动状态
                    this.classList.add('active');
                    
                    // 显示消息面板
                    document.getElementById(`message-panel-${serverId}`).style.display = 'block';
                    
                    // 加载消息
                    loadMessages(connection);
                });
            });
        })
        .catch(error => console.error('Error loading connections:', error));
}

// 加载消息
function loadMessages(connection) {
    const messagesContainer = document.getElementById(`messages-${connection.serverId}`);
    messagesContainer.innerHTML = '';
    
    if (!connection.messages || connection.messages.length === 0) {
        messagesContainer.innerHTML = '<div class="text-center p-3 text-muted">暂无消息</div>';
        return;
    }
    
    connection.messages.forEach(message => {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${message.direction === 'INBOUND' ? 'message-in' : 'message-out'}`;
        messageDiv.innerHTML = `
            <div class="message-header">
                <span class="badge ${message.direction === 'INBOUND' ? 'bg-primary' : 'bg-success'}">
                    ${message.direction === 'INBOUND' ? '接收' : '发送'}
                </span>
                <span class="badge bg-secondary">${message.contentType}</span>
                <span class="text-muted small">${formatDateTime(message.timestamp)}</span>
            </div>
            <div class="message-content">
                <pre>${message.content}</pre>
            </div>
        `;
        messagesContainer.appendChild(messageDiv);
    });
    
    // 滚动到底部
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}

// 发送消息
function sendMessage(connectionId, message, contentType) {
    if (!message) return;
    
    fetch(`/api/servers/connections/${connectionId}/send`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            message: message,
            contentType: contentType
        })
    })
    .then(response => {
        if (response.ok) {
            // 清空消息输入框
            const serverId = document.querySelector(`.connection-item[data-connection-id="${connectionId}"]`)
                .closest('[id^="connections-"]').id.split('-')[1];
            document.getElementById(`message-input-${serverId}`).value = '';
        }
    })
    .catch(error => console.error('Error sending message:', error));
}

// 启动服务器
function startServer(serverId) {
    fetch(`/api/servers/${serverId}/start`, {
        method: 'POST'
    })
    .then(response => {
        if (response.ok) {
            loadServerList();
        }
    })
    .catch(error => console.error('Error starting server:', error));
}

// 停止服务器
function stopServer(serverId) {
    fetch(`/api/servers/${serverId}/stop`, {
        method: 'POST'
    })
    .then(response => {
        if (response.ok) {
            loadServerList();
        }
    })
    .catch(error => console.error('Error stopping server:', error));
}

// 编辑服务器
function editServer(server) {
    document.getElementById('serverModalTitle').textContent = '编辑服务';
    document.getElementById('serverId').value = server.id;
    document.getElementById('serverName').value = server.name;
    document.getElementById('serverType').value = server.type;
    document.getElementById('serverPort').value = server.port;
    document.getElementById('responseMode').value = server.responseMode;
    document.getElementById('responseContent').value = server.responseContent || '';
    
    updateResponseContentVisibility();
    
    const serverModal = new bootstrap.Modal(document.getElementById('serverModal'));
    serverModal.show();
}

// 删除服务器
function deleteServer(serverId) {
    if (!confirm('确定要删除此服务吗？')) return;
    
    fetch(`/api/servers/${serverId}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (response.ok) {
            loadServerList();
            
            // 关闭相关标签页
            const tab = document.getElementById(`tab-${serverId}`);
            if (tab) {
                tab.querySelector('.btn-close').click();
            }
        }
    })
    .catch(error => console.error('Error deleting server:', error));
}

// 保存服务器
function saveServer() {
    const serverId = document.getElementById('serverId').value;
    const serverName = document.getElementById('serverName').value;
    const serverType = document.getElementById('serverType').value;
    const serverPort = document.getElementById('serverPort').value;
    const responseMode = document.getElementById('responseMode').value;
    const responseContent = document.getElementById('responseContent').value;
    
    if (!serverName || !serverPort) {
        alert('请填写服务名称和端口');
        return;
    }
    
    const serverData = {
        name: serverName,
        type: serverType,
        port: parseInt(serverPort),
        responseMode: responseMode,
        responseContent: responseContent
    };
    
    if (serverId) {
        // 更新服务器
        fetch(`/api/servers/${serverId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(serverData)
        })
        .then(response => {
            if (response.ok) {
                bootstrap.Modal.getInstance(document.getElementById('serverModal')).hide();
                loadServerList();
            }
        })
        .catch(error => console.error('Error updating server:', error));
    } else {
        // 创建新服务器
        fetch('/api/servers', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(serverData)
        })
        .then(response => response.json())
        .then(data => {
            bootstrap.Modal.getInstance(document.getElementById('serverModal')).hide();
            loadServerList();
        })
        .catch(error => console.error('Error creating server:', error));
    }
}

// 更新响应内容可见性
function updateResponseContentVisibility() {
    const responseMode = document.getElementById('responseMode').value;
    const responseContentGroup = document.getElementById('responseContentGroup');
    
    if (responseMode === 'AUTO') {
        responseContentGroup.style.display = 'block';
    } else {
        responseContentGroup.style.display = 'none';
    }
}

// 设置WebSocket连接
function setupWebSocket() {
    const socket = new WebSocket(`ws://${window.location.host}/ws`);
    
    socket.onmessage = function(event) {
        const data = JSON.parse(event.data);
        
        switch (data.type) {
            case 'SERVER_STATUS_CHANGED':
                loadServerList();
                break;
                
            case 'CONNECTION_ADDED':
                loadConnections(data.connection.serverId);
                break;
                
            case 'CONNECTION_REMOVED':
                loadServerList();
                break;
                
            case 'MESSAGE_ADDED':
                const activeConnection = document.querySelector('.connection-item.active');
                if (activeConnection && activeConnection.dataset.connectionId === data.connectionId) {
                    fetch(`/api/servers/connections/${data.connectionId}`)
                        .then(response => response.json())
                        .then(connection => loadMessages(connection))
                        .catch(error => console.error('Error loading connection:', error));
                }
                break;
        }
    };
    
    socket.onclose = function() {
        // 尝试重新连接
        setTimeout(setupWebSocket, 5000);
    };
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';
    const date = new Date(dateTimeStr);
    return date.toLocaleString();
}

// 获取响应模式名称
function getResponseModeName(mode) {
    switch (mode) {
        case 'MANUAL': return '手动响应';
        case 'AUTO': return '自动响应';
        case 'ECHO': return '回显';
        default: return mode;
    }
}

// 退出登录
function logout() {
    fetch('/api/auth/logout', {
        method: 'POST'
    })
    .then(response => {
        if (response.ok) {
            window.location.href = '/login.html';
        }
    })
    .catch(error => console.error('Error logging out:', error));
}